'''xpath_案例3爬取肯德基桌面壁纸'''

# 引入操作网络请求包
import urllib.request
import urllib.parse
# 引入解析html包
from lxml import etree
# 引入操作文件包
import os
# 引入操作时间包
import time


# 构造一个Request
def build_request(page):
    kdj_url = 'http://www.kfc.com.cn/kfccda/ashx/GetDownLoad.ashx'
    kdj_headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/103.0.0.0 Safari/537.36'
    }
    kdj_body = {
        'pageNum': page,
        'pageSize': 20,
        'type': 1
    }
    kdj_body = urllib.parse.urlencode(kdj_body).encode('utf-8')
    request = urllib.request.Request(url=kdj_url, headers=kdj_headers, data=kdj_body)
    return request


# 获取请求结果
def get_result(request):
    response = urllib.request.urlopen(request)
    result = response.read().decode('utf-8')
    return result


# 下载图片到本地
def down_img(page, img_list):
    # 保证local_path 路径必须存在；
    local_path = 'D:\\hxy\\test\\爬取肯德基'
    save_local_pth = local_path+'\\'+str(page)
    exitFlag = os.path.exists(save_local_pth)
    if exitFlag == False:
        # 当文件不存在生成文件夹
        os.mkdir(save_local_pth)

    for index in range(len(img_list)):
        # print(img_list[index])
        img_url = 'https://www.kfc.com.cn/kfccda/{0}'.format(img_list[index])
        print(img_url)
        save_img = save_local_pth+'\\'+time.strftime('%Y-%m-%d%H%M%S', time.localtime())+'.jpg'
        print(f'打印保存文件名称：{save_img}')
        urllib.request.urlretrieve(img_url, save_img)


if __name__ == '__main__':
    start_num = int(input('请输入起始页：'))
    end_num = int(input('请输入终止页：'))
    # 三元运算符 控制用户输入的起始页值 只能是1
    start_num = 1 if start_num <= 0 else start_num
    for page in range(start_num, end_num+1):
        request = build_request(page)
        result = get_result(request)
        # xpath解析html
        html = etree.HTML(result)
        img_list = html.xpath('//div[@class="down"]/img/@src')
        print(len(img_list), img_list)
        down_img(page, img_list)



'''
#初始示例
kdj_url = 'http://www.kfc.com.cn/kfccda/ashx/GetDownLoad.ashx'
kdj_headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/103.0.0.0 Safari/537.36'
}
kdj_body = {
    'pageNum': 1,
    'pageSize': 20,
    'type': 1
}
# post请求体必须编码
kdj_body = urllib.parse.urlencode(kdj_body).encode('utf-8')
request = urllib.request.Request(url=kdj_url, headers=kdj_headers, data=kdj_body)
response = urllib.request.urlopen(request)
content = response.read().decode('utf-8')
print(content)
html = etree.HTML(content)
img_list = html.xpath('//div[@class="down"]/img/@src')
print(len(img_list), img_list)
for index in range(len(img_list)):
    # print(img_list[index])
    img_url = 'https://www.kfc.com.cn/kfccda/{0}'.format(img_list[index])
    print(img_url)
'''

